package com.buric.common.utils;

import cn.hutool.core.map.MapUtil;
import com.alibaba.ttl.TransmittableThreadLocal;
import com.buric.common.constant.ContextConstants;
import lombok.extern.slf4j.Slf4j;
import java.util.HashMap;
import java.util.Map;


/**
 * @author: zhou.wei
 * @description 用户上下文信息
 * @date: 2024/5/9 13:16
 */
@Slf4j
public class ContextHolder {

    /**
     * 构造方法私有化
     */
    private ContextHolder(){}

    /**
     * 线程本地变量
     * 使用 Map 存储 key-value 数据，便于扩展
     */
    private static final TransmittableThreadLocal<Map<String, Object>> HOLDER = new TransmittableThreadLocal<>();

    /**
     * 添加数据 key-value
     * @param key key
     * @param value value
     */
    public static void set(String key, Object value){
        Map<String, Object> params = HOLDER.get();
        if (params == null){
            HOLDER.set(new HashMap<>());
        }
        HOLDER.get().put(key, value);
    }

    public static Map<String, Object> get(){
        return HOLDER.get();
    }

    public static Long getUserId(){
        return MapUtil.getLong(HOLDER.get(), ContextConstants.USER_ID);
    }

    public static String getStringValue(String key){
        return MapUtil.getStr(HOLDER.get(), key);
    }

    public static Long getLongValue(String key){
        return MapUtil.getLong(HOLDER.get(), key);
    }

    public static void remove(){
        HOLDER.remove();
    }
}
